import Pyro.core, os, time, remotes, sys, db, getpass, const, urllib2, hashlib, socket, config 
  
def start_server(name_server, event_server, pyro_server):
    name_server.start()
    name_server.waitUntilStarted()         # wait until the NS has fully started.
    event_server.start()
    event_server.waitUntilStarted()        # wait until the ES has fully started.
    pyro_server.start()
    while not pyro_server.ready:           # wait until the PYRO has fully started.
        time.sleep(1)

def show_menu(name_server, event_server, pyro_server):
    while 1:
        cls()
        print "--------------BLENDER-----------------"
        print "Choose an option:"
        print "1 - Manage Blender"
        print "2 - Manage the crowd"
        print "3 - Manage members database"
        print "q - quit application"
        print "--------------------------------------"
        inp = raw_input(">>: ")
        print "\n"        
        if inp == '1':
            show_blender_menu(name_server, event_server, pyro_server)
        elif inp == '2':
            show_crowd_menu(name_server, event_server, pyro_server)          
        elif inp == '3':
            show_members_menu(name_server, event_server, pyro_server)
        elif inp == 'q':
            quit(name_server, event_server, pyro_server)
        else:
            print "Please choose one available option!"
        time.sleep(1)
        
        
def show_blender_menu(name_server, event_server, pyro_server):
    while 1:
        cls()
        print "--------------BLENDER-----------------"
        print "1 - View Blender's status"
        print "b - back"
        print "--------------------------------------"
        inp = raw_input(">>: ")
        print "\n"
        if inp == '1':
            print pyro_server
            print name_server
            print event_server
            print pyro_server.blender_daemon
            print pyro_server.blender_daemon.crowd
            print "Name server URI: " + str(pyro_server.blender_daemon.NameServer.URI)
            raw_input('Press enter to continue...')
        elif inp == 'b':
            break
        time.sleep(1)   
        

def show_crowd_menu(name_server, event_server, pyro_server):
    while 1:
        cls()
        print "-----------------------BLENDER---------------------------"
        print "Choose an option:"
        print "1 - View current logged users"
        print "2 - View current active nodes"
        print "3 - View current waiting members"
        print "4 - Accept waiting members into the crowd (Join Commit)"
        print "b - back"
        print "---------------------------------------------------------"
        inp = raw_input(">>: ")
        print "\n"
        if inp == '1':
            print "-----------CURRENT LOGGED USERS-----------"
            if pyro_server.blender_daemon.crowd:
                pyro_server.blender_daemon.crowd.show_logged_users() 
                raw_input('\nPress enter to continue...')
        elif inp == '2':
            print "-----------CURRENT ACTIVE NODES-----------"
            if pyro_server.blender_daemon.crowd:
                pyro_server.blender_daemon.crowd.show_active_members()
                raw_input('\nPress enter to continue...')
        elif inp == '3':
            print "-----------USERS IN WAITING LIST-----------"
            if pyro_server.blender_daemon.crowd:
                pyro_server.blender_daemon.crowd.show_waiting_members()
                raw_input('\nPress enter to continue...')
        elif inp == '4':            
            if pyro_server.blender_daemon.crowd.join_commit():
                print "\nJoin Commit sent to jondos!"
            else:
                print "\nJoin Commit failed..."
        elif inp == 'b':
            break
        time.sleep(1)
        
def show_members_menu(name_server, event_server, pyro_server):
    db_man = db.DbManager()
    db_man.connect(const.DB_NAME)
    while 1:
        cls()
        print "-----------------------BLENDER---------------------------"
        print "Choose an option:"
        print "1 - View registered members"
        print "2 - Register new member on database"
        print "3 - Delete member from database"
        print "4 - Flush all members from database"
        print "b - back"
        print "---------------------------------------------------------"
        inp = raw_input(">>: ")
        print "\n"
        if inp == '1':
            print "---------CURRENT REGISTERED MEMBERS---------------"
            for usr in db_man.get_members():
                print usr[0]
            inp = raw_input('Press enter to continue...')            
        elif inp == '2':            
            print "Please fill the informations below"            
            while 1:
                login = raw_input("Enter user name: ")
                password = getpass.getpass("Enter password: ")
                password_rep = getpass.getpass("Re-enter password: ")
                if  password == password_rep:
                    break
                else:
                    print "Entered password mismatch! Try again..."
            db_man.connect(const.DB_NAME)
            if db_man.add_member(login, hashlib.md5(password).hexdigest()): #@UndefinedVariable
                print "User " + login + " added successfully!"
            else:
                print "Error adding user " + login
        elif inp == '3':
            inp = raw_input("Type the username you want to delete: ")
            if inp:
                pass
            else:
                print "Username cannot be empty!"
        elif inp == '4':
            inp = raw_input("Delete all registered members [y/n]?: ")
            if inp == 'y':
                if db_man.flush_members():
                    print "All members deleted!"
                else:
                    print "Unable to delete members"
        elif inp == 'b':            
            db_man.close()
            break
        time.sleep(1)
    

def quit(name_server, event_server, pyro_server):
    inp = raw_input( "Really exit?[y/n]: ")           
    if inp == 'y':
        print "Bye!"
        sys.exit()
        
def cls():
    os.system(['clear','cls'][os.name == 'nt'])

def main():
    pub_ip = socket.gethostbyname(socket.gethostname())
    inp = raw_input("Bind service to public ip? [y/n]: ")
    if inp == 'y':
        try:
            pub_ip = urllib2.urlopen(config.RMT_ADDRESS).read()
            print "Blender public ip is : " + pub_ip
        except urllib2.URLError:
            print "Unable to read http://whatismyip.org"
    print "All running service will bind to this ip: " + pub_ip 
    print "Check your firewall to open all the ports needed"
    Pyro.config.PYRO_PUBLISHHOST = pub_ip
    name_server = remotes.NameServer()
    event_server = remotes.EventServer()   
    pyro_server = remotes.PyroServer()    
    start_server(name_server, event_server, pyro_server)
    show_menu(name_server, event_server, pyro_server)

if __name__=="__main__":
    main()


